import { formatSuccessResponse } from '../utils/errors.js';
import { authenticate } from '../middleware/auth.js';
import { validateRequest, userPreferencesSchema } from '../utils/validation.js';

export default async function userRoutes(fastify, options) {
  
  /**
   * 获取用户偏好设置
   */
  fastify.get('/preferences', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    let preferences = await fastify.prisma.userPreference.findUnique({
      where: { userId: request.user.userId },
    });
    
    // 如果不存在则创建默认设置
    if (!preferences) {
      preferences = await fastify.prisma.userPreference.create({
        data: { userId: request.user.userId },
      });
    }
    
    return formatSuccessResponse(preferences);
  });
  
  /**
   * 更新用户偏好设置
   */
  fastify.put('/preferences', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const data = validateRequest(userPreferencesSchema, request.body);
    
    const preferences = await fastify.prisma.userPreference.upsert({
      where: { userId: request.user.userId },
      update: data,
      create: {
        userId: request.user.userId,
        ...data,
      },
    });
    
    return formatSuccessResponse(preferences, '偏好设置更新成功');
  });
  
  /**
   * 获取用户分类
   */
  fastify.get('/categories', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const categories = await fastify.prisma.category.findMany({
      where: { userId: request.user.userId },
      orderBy: { sortOrder: 'asc' },
    });
    
    return formatSuccessResponse(categories);
  });
  
  /**
   * 创建分类
   */
  fastify.post('/categories', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const { name, color, icon, sortOrder } = request.body;
    
    const category = await fastify.prisma.category.create({
      data: {
        userId: request.user.userId,
        name,
        color,
        icon,
        sortOrder: sortOrder || 0,
      },
    });
    
    return formatSuccessResponse(category, '分类创建成功');
  });
  
  /**
   * 更新分类
   */
  fastify.put('/categories/:id', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    const { name, color, icon, sortOrder } = request.body;
    
    const category = await fastify.prisma.category.updateMany({
      where: {
        id: request.params.id,
        userId: request.user.userId,
      },
      data: { name, color, icon, sortOrder },
    });
    
    return formatSuccessResponse(category, '分类更新成功');
  });
  
  /**
   * 删除分类
   */
  fastify.delete('/categories/:id', {
    onRequest: [authenticate],
  }, async (request, reply) => {
    await fastify.prisma.category.deleteMany({
      where: {
        id: request.params.id,
        userId: request.user.userId,
      },
    });
    
    return formatSuccessResponse(null, '分类删除成功');
  });
}


